package com.aiit.controller;


import com.aiit.pojo.User;
import com.aiit.pojo.UserVo;
import com.aiit.service.IUserService;

import com.aiit.util.MD5utils;
import com.aiit.util.VerifyCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.stream.events.Comment;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("/admin")
public class UserController {
    @Autowired
//    @Lazy
    private IUserService userService;
    @GetMapping("/login")
    public String getLogin() {
        return "/admin/login2";
    }
    @RequestMapping("/login")
    public String doLogin(UserVo user, Model model, HttpServletRequest request,
                            HttpServletResponse response, HttpSession session)  {
////        校验验证码
////        session中的验证码
//        String verifyCode=(String) session.getAttribute("verifyCode");
//        JSONObject result=new JSONObject();
//        if(!imageCode.equals(verifyCode)){
//            result.put("success", false);
//            result.put("errorInfo", "验证码填写错误!");
//            return "admin/login2";
//        }
        Subject subject = SecurityUtils.getSubject();
        String password = user.getPasswordNew() ;//这是原始密码
        //把原密码加密
        String newPassWord = MD5utils.code(user.getPasswordNew());
        User user1 = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsernameNew()));
//        request.getSession().setAttribute("type", user1.getRoles());
//        model.addAttribute("type", user1.getRoles());
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsernameNew(), newPassWord);//加密密码 功能完成以后 把加密密码传进去
        try {
            subject.login(token);
//            token.setRememberMe(false);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            model.addAttribute("rat", "用户名不存在");
            return "/admin/login2";
        } catch (LockedAccountException e) {
            e.printStackTrace();
            model.addAttribute("rlt", "账户被锁定");
            return "/admin/login2";
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            model.addAttribute("rlt", "密码错误");
            return "/admin/login2";
        }
        model.addAttribute("rlt", 1);
//        if (user1.getRoles() == 1) {
//            return "admin/index";
//        } else if (user1.getRoles() == 2) {
//            return "user/index";
//        } else {
//            return "admin/login2";
//        }
        return "/main/main";
    }
    @GetMapping("/regist")
    public String getRegist() {
        return "/admin/login2";
    }
    @RequestMapping("/regist")
    public String doRegist(User user) {
//        user.setRoles(1);
         //把原密码加密
        user.setPassword(MD5utils.code(user.getPassword()));
        int rlt = userService.insert(user);
//        userService.insert(user);
//        User user_id=userService.getById(user.getId());
//        int r=userService.insert2(user_id);
        userService.insert2(user);
        if (rlt == 0) {
            System.out.println("注册失败");
        } else {
            System.out.println("注册成功");
        }
        return "/admin/login2";
    }
    @RequestMapping("/getVerifyCode")
    @ResponseBody
    public void getVerificationCode(HttpServletResponse response, HttpServletRequest request) {
        try {
            int width = 200;
            int height = 69;

            BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//生成对应宽高的初始图片
            String randomText = VerifyCode.drawRandomText(width, height, verifyImg);//单独的一个类方法，出于代码复用考虑，进行了封装。功能是生成验证码字符并加上噪点，干扰线，返回值为验证码字符

            request.getSession().setAttribute("verifyCode", randomText);
            response.setContentType("/image/png");//必须设置响应内容类型为图片，否则前台不识别


            OutputStream os = response.getOutputStream(); //获取文件输出流
            ImageIO.write(verifyImg, "png", os);//输出图片流
            os.flush();
            os.close();//关闭流
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/selfinformation")
    public String selfinformation(){
        return "/main/selfinformation";
    }
    @RequestMapping("/main")
    public String toMain(){
        return "/main/main";
    }
}
